package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 指定时间内的区间，营业额数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Double> turnoverList=new ArrayList<>();
        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        String data = StringUtils.join(dateList, ",");
        String turnover = StringUtils.join(turnoverList, ",");
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(data)
                .turnoverList(turnover)
                .build();
        return reportVO;
    }

    /**
     * 用户数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> totalUser=new ArrayList<>();
        List<Integer> newUser=new ArrayList<>();
        Map map=new HashMap();
        for(LocalDate date1:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date1, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date1, LocalTime.MAX);
            map.put("end",endTime);
            //总用户数量
            Integer totalU = userMapper.countMap(map);
            map.put("begin",beginTime);
            //新增用户数量
            Integer newU = userMapper.countMap(map);
            //添加数据
            totalUser.add(totalU);
            newUser.add(newU);
        }
        //处理，封装数据
        String date=StringUtils.join(dateList,",");
        String totalUsers = StringUtils.join(totalUser, ",");
        String newUsers = StringUtils.join(newUser, ",");
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(date)
                .newUserList(newUsers)
                .totalUserList(totalUsers)
                .build();
        return userReportVO;
    }

    /**
     * 指定时间内的区间，订单数量统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        //存放每天的订单数
        List<Integer> orders=new ArrayList<>();
        //存放每天的有效订单数
        List<Integer> validOrders=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的订单总数
            Integer orderCounts=getOrderCounts(beginTime,endTime,null);
            orders.add(orderCounts);
            //查询每天的有效订单数
            Integer validCounts=getOrderCounts(beginTime,endTime,Orders.COMPLETED);
            validOrders.add(validCounts);
        }
        //计算时间区间内的订单总数量
        Integer totalOrders = orders.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单总数量
        Integer totalValidOrders = validOrders.stream().reduce(Integer::sum).get();
        //计算订单完成率（有效订单数/总订单数*100%）
        Double orderCompletionRate=0.0;
        if(totalValidOrders!=0){
            orderCompletionRate=totalValidOrders.doubleValue()/totalOrders;
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orders, ","))
                .validOrderCountList(StringUtils.join(validOrders, ","))
                .totalOrderCount(totalOrders)
                .validOrderCount(totalValidOrders)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    private Integer getOrderCounts(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map=new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        Integer counts = orderMapper.orderCounts(map);
        return counts;
    }

    /**
     * 菜品销量top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getsaleTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);
        List<GoodsSalesDTO> saleTop10 = orderMapper.getSaleTop(beginTime, endTime);
        List<String> names = saleTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = saleTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String namesList=StringUtils.join(names,",");
        String numbersList=StringUtils.join(numbers,",");
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(namesList)
                .numberList(numbersList)
                .build();
        return salesTop10ReportVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate beginDate=LocalDate.now().minusDays(30);
        LocalDate endData=LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endData, LocalTime.MAX));

        //2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/excel.xlsx");

        try{
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel=new XSSFWorkbook(in);
            //根据名字，获取表格文件的Sheet页
            XSSFSheet sheet=excel.getSheet("Sheet1");

            //往第二行第二格中填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间:"+beginDate+"至"+endData);

            //获得第四行
            XSSFRow row=sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获得第五行
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date=beginDate.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO detailBusinessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(detailBusinessData.getTurnover());
                row.getCell(3).setCellValue(detailBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(detailBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(detailBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(detailBusinessData.getNewUsers());

            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e){
            e.printStackTrace();
        }

    }

}
